
import { isHotkey } from "is-hotkey";
export class KeyboardEvent {
    constructor (editor, container, view) {
        this.editor = editor;
        this.container = container;
        this.view = view
        this.isComposing = false // 是否处理中文输入过程中
    }

    compositionStartHandler_ (e) {
        this.isComposing = true
    }

    compositionEndHandler_ (e) {
        this.isComposing = false
        const text = e.data;
        if (text) {
            this.editor.insertTextAtCursor(text);
        }
    }

    beforeInputHandler_ (e) {
        const inputType = e.inputType;
        if (inputType === 'insertCompositionText' || inputType === 'deleteCompositionText') {
            return
        }
        e.preventDefault(); // 阻止默认的输入显示
        let text = null
        switch (inputType) {
            case 'insertText': 
                text = e.data;
                if (text) {
                    this.editor.insertTextAtCursor(text);
                }
                break;
            case 'insertParagraph':
                this.editor.insertTextAtCursor('\n');
                break;

            case 'deleteContentBackward':
                this.editor.deleteTextAtCursor()
                break

            case 'insertFromPaste':
                const data = e.dataTransfer
                text = data.getData('text/plain')
                if (text) {
                    this.editor.insertTextAtCursor(text);
                }
        }
        
    }
    keydownHandler_ (e) {
        // if (撤销) { // 可以用 is-hotkey 判断组合键
        //     e.preventDefault()
        //     this.editor.undo && this.editor.undo()
        // } else if (回退) {
        //     this.editor.redo && this.editor.redo()
        // }
    }

    selectionchangeHandler_ (selection) {
        if (selection && !this.isComposing) {
            this.editor.setSelection(selection.anchor, selection.focus)
        }
    }
    addListeners() {
        this.container.addEventListener('beforeinput', this.beforeInputHandler_.bind(this))
        this.container.addEventListener('keydown', this.keydownHandler_.bind(this))
        this.container.addEventListener('compositionstart', this.compositionStartHandler_.bind(this))
        this.container.addEventListener('compositionend', this.compositionEndHandler_.bind(this))
        this.view.on('selection-change', this.selectionchangeHandler_.bind(this))
    }
}
export default KeyboardEvent;